package com.yunsc.common.utils;

import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @version: 1.0
 * @Author: adan
 * @description:
 * @date: 2024-05-05 18:34
 */
public class VerifyCodeUtil {

    /**
     * 生成验证码base64字符串
     *
     * @param code
     * @return
     * @throws IOException
     */
    public static String createVerifyCode(String code) throws IOException {
        BufferedImage image = createImage(code);
        return imageToBase64(image);
    }

    /**
     * 生成验证码图片
     *
     * @param code
     * @return
     * @throws IOException
     */
    public static BufferedImage createImage(String code) throws IOException {
        int width = 100;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics2D g = image.createGraphics();
        // 设定背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        // 设定字体
        Font font = new Font("Arial", Font.PLAIN, 24);
        g.setFont(font);
        // 画干扰线
        for (int i = 0; i < 10; i++) {
            int x1 = (int) (Math.random() * width);
            int y1 = (int) (Math.random() * height);
            int x2 = (int) (Math.random() * width);
            int y2 = (int) (Math.random() * height);
            g.setColor(Color.BLACK);
            g.drawLine(x1, y1, x2, y2);
        }
        // 画验证码
        g.setColor(Color.BLUE);
        for (int i = 0; i < code.length(); i++) {
            int x = (int) (Math.random() * 10) + 20;
            int y = (int) (Math.random() * 10) + 20;
            g.drawString(code.charAt(i) + "", x, y);
        }
        g.dispose();
        return image;
    }


    /**
     * 文件BufferedImage类型转BASE64
     *
     * @param bufferedImage
     * @return
     */
    public static String imageToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "png", baos);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        return "data:image/png;base64," + png_base64;

    }

}
